package com.household.security.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.household.domain.entity.User;
import com.household.domain.enums.ResponseErrorCodeEnum;
import com.household.mapper.UserMapper;
import com.household.security.exception.DefaultAuthenException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * Created By wanzhen
 * 2023. 2023/3/25. 13:47
 */
@Service
public class MyUserDetailsService implements UserDetailsService, UserDetailsPasswordService {

    private final UserMapper userMapper;

    public MyUserDetailsService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer updatePassword = userMapper.updatePassword(user.getUsername(), newPassword);
        if (updatePassword==1){
            ((User)user).setPassword(newPassword);
        }
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(user))throw new DefaultAuthenException(ResponseErrorCodeEnum.USER_NOT_EXIST);
        return user;
    }

}
